<?php

namespace App\Admin\Controllers;

use App\Models\PlatUser;

use App\Models\RechargeGroup;
use App\Models\RechargeSplitMode;
use App\Models\SettleGroup;
use App\Presenters\Admin\PlatUserPresenter;
use App\Services\RechargePaymentsService;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;

class PlatUserController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {

        return Admin::content(function (Content $content) {

            $content->header('平台用户管理 列表');
            $content->description('');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $plat_user = PlatUser::find($id);

            $content->header(" {$plat_user->username}修改");
            $content->description("{$plat_user->code}");

            $content->body($this->form($id)->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('用户新增');
            $content->description('');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(PlatUser::class, function (Grid $grid) {

            $grid->id('ID')->sortable();
            $grid->code('用户编号');

            $grid->username('用户名');
            $grid->column('phone' ,'手机号');
            $grid->status('账户状态')->display(function ($status) {
                return PlatUserPresenter::showStatus($status);
            });
            $grid->column('profile.status', '认证状态')->display(function ($status) {
                return PlatUserPresenter::showAuditStatus($status);
            });
            $grid->column('profile.property', '账户认证性质')->display(function ($type) {
                return is_null($type) ? '-' : ($type ? '企业' : '个人');
            });
            $grid->column('profile.role', '账户认证类型')->display(function ($role) {
                return is_null($role) ? '-' : config('dictionary.user_roles.'.$role);
            });
            $states = [
                'on'  => ['value' => 1, 'text' => '开启', 'color' => 'primary'],
                'off' => ['value' => 0, 'text' => '关闭', 'color' => 'default'],
            ];
            $grid->recharge_api('支付api')->switch($states);
            $grid->column('recharge_mode', '分组模式')->display(function ($mode) {
                $group = RechargeGroup::find($this->recharge_gid);
                $name = $group ? $group->name : 'null';
                return $mode == 0 ? '个人' : '['. $name.']';
            });
            $grid->column('settle_gid', '结算分组')->display(function ($gid) {
                return $gid == 0 ? '无分组' : SettleGroup::find($gid)->name;
            });
            $grid->column('upper.code', '上级用户')->display(function ($value) {
                return $this->role == 0 ? ($value ? : '-') : '-';
            });
            $grid->created_at('注册时间');
            $grid->last_at('上次登录时间');
            $grid->last_ip('上次登录ip');
            $grid->actions(function ($actions) {
                $actions->append('<a href="'.route('platusers.payments', $actions->getKey()).'"><i class="fa fa-sliders"></i> 通道分配</a>');
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @param null $id
     *
     * @return \Encore\Admin\Form
     */
    protected function form($id=null)
    {
        return Admin::form(PlatUser::class, function (Form $form) use ($id){
//            Admin::script('initSelect();');
            $platuser = $id ? PlatUser::find($id):null;

            $form->tab('基本信息', function (Form $form) use ($platuser, $id) {
                $form->display('code', '用户编号');
                if ($id) {
                    $form->display('username', '用户账户');
                } else {
                    $form->text('username', '登录邮箱')->placeholder('输入登录邮箱')
                        ->rules('required|max:100|unique:plat_users,username|email');
                }

                $form->password('password', '用户密码')
                    ->placeholder($id ? '输入新密码更改密码': '输入登录密码');
                $form->password('trade_pwd', '交易密码');
                $form->text('phone', '手机号')->rules('required|regex:/^1[34578][0-9]{9}$/');
                $form->select('status', '账户状态')->options([
                    -1 => '停用',
                    0 => '正常',
                    1 => '冻结'
                ])->default(0)->rules('required');
                $form->text('qq', 'qq号码')->rules('nullable|regex:/^[1-9][0-9]{4,14}$/');
                $form->text('contact', '联系人姓名')->rules('nullable');
                $form->display('key', '用户密钥');
            })->tab('认证信息', function (Form $form) use ($platuser, $id) {
                $form->select('profile.property', '认证性质')->options([
                    0 => '个人',
                    1 => '企业'
                ]);
                $form->select('profile.status', '审核状态')->options([
                    0 => '未审核',
                    1 => '已审核',
                    2 => '审核拒绝'
                ]);
                $form->text('profile.remark', '备注信息')->rules('nullable|max:500')->help('拒绝应用通过时作为拒绝理由展示给用户端');
                $form->text('profile.realname', '实名认证')->rules('required|max:150');
                $form->text('profile.idcard', '实名身份证')->rules('required|max:20');
                $form->text('profile.enterprise', '企业名称')->rules('required_if:property,1|max:255');
                $form->text('profile.license', '工商信息编码')->rules('required_if:property,1|max:50');
                $form->display('profile.full_addr', '地址所在地');
                $form->display('profile.created_at', '资料提交时间');
            })->tab('认证资料图片', function (Form $form) {
                $form->image('profile.img_id_hand', '手持证件照');
                $form->image('profile.img_id_front', '证件照正面');
                $form->image('profile.img_id_back', '证件照背面');
                $form->image('profile.img_license', '企业工商信息照');
                $form->image('profile.img_tax', '税务信息照');
                $form->image('profile.img_permit', '文网文附件照');
            })->tab('风控信息', function (Form $form) use ($platuser, $id) {
                $form->select('profile.role', '账户认证角色')
                    ->options(config('dictionary.user_roles'))
                    ->default(0)
                    ->load('settle_gid', route('api.platuser.settlegroup'))
                    ->load('recharge_gid', route('api.platuser.rechargegroup'));
                $form->radio('is_withdraw', '允许提现')->options([
                    0 => '不允许',
                    1 => '允许'
                ])->default(0);
                $form->radio('settle_type', '结算类型')->options([
                    0 => '平台结算',
                    1 => 'api结算'
                ]);
                $states = [
                    'on'  => ['value' => 1, 'text' => '开启', 'color' => 'primary'],
                    'off' => ['value' => 0, 'text' => '关闭', 'color' => 'default'],
                ];
                $form->switch('recharge_api', '支付api功能')->states($states);
                $form->switch('settle_api', '结算api功能')->states($states);

                $form->number('settle_cycle', '结算周期(t+)')->default(0)->rules('numeric|min:0');
                $form->select('recharge_mode', '交易模式')->options([
                    0 => '按个人',
                    1 => '按分组'
                ])->default(1)->rules('required');
                $classify = $id ? ($platuser->profile ? $platuser->profile->role : 0) : 0;
                $form->select('recharge_gid', '交易分组')
                    ->options(function () use ($classify){
                        $groups = RechargeGroup::where('classify', $classify)
                            ->orderBy('is_default', 'desc')
                            ->pluck('name', 'id');
                        return count($groups)? $groups: [0 => '无分组'];
                    })->rules('required');
                $form->select('settle_gid', '结算分组')->options(function() use ($classify) {
                    $groups = SettleGroup::where('classify', $classify)
                        ->orderBy('is_default', 'desc')
                        ->pluck('name', 'id');
                    return  count($groups) ? $groups : [0 => '无分组'];
                })->rules('nullable');
                $proxy = PlatUser::proxy()->audited()->where('id', '<>', $id)->get()->pluck('code', 'id')->toArray();
                $form->select('upper_id', '上级')
                    ->options([0=>'无'] + $proxy)->default(0)->rules('required')->help('账户角色为商户时上级有效');
            });
            $form->saving(function (Form $form) {
                if ($form->password && $form->model()->password != $form->password) {
                    $form->password = password_hash($form->password, PASSWORD_DEFAULT);
                }
                if ($form->trade_pwd && $form->model()->trade_pwd != $form->trade_pwd) {
                    $form->trade_pwd = password_hash($form->trade_pwd, PASSWORD_DEFAULT);
                }
                $profile = $form->model()->profile;
                if (is_array($form->profile)) {
                    $profile->update($form->profile);
                }
            });
        });
    }

    public function payments(Request $request, $id)
    {
        return RechargePaymentsService::allocatePayments($request, $id, 'single');
    }
}
